package com.dongzili.common.disruptor.service;

import com.dongzili.common.disruptor.entity.MessageEvent;
import com.dongzili.common.disruptor.handler.EventHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
public class MessageProcessor<T> {

    private final Map<Class<?>, EventHandler<T>> handlers = new ConcurrentHashMap<>();

    // Spring 会自动将所有 EventHandler 实现注入到 Map 中
    public MessageProcessor(Map<String, EventHandler<T>> handlerMap) {

        handlerMap.forEach((beanName, handler) -> {
            if (handler != null) {
                try{
                    handlers.put(handler.getTypeParam(), handler);
                }catch (Exception ignore){
//                    System.out.println(handler.getClass().getName()+", "+ ignore.getLocalizedMessage());
//                    System.out.println(Arrays.stream(handler.getClass().getMethods()).map(Method::getName).collect(Collectors.toList()));
                }
            }

        });

    }
    public void process(Class<?> clazz, MessageEvent<T> event) {
        EventHandler<T> handler = handlers.get(clazz);
        if (handler != null) {
            handler.send(event);
        } else {
            System.out.println("没有找到对应的处理器: " + clazz.getName());
        }
    }
}